import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from sklearn.metrics import silhouette_score

class ClusterUtils(object):
    def __init__(self):
        self.df = pd.read_csv('scenic_data.csv')
    def get_k(self):
        """
        获取合适的k值

        """
        features = self.df[['non_weekend_ratio','eldery_ratio','out_province_ratio']]
        # 数据标准化
        scaler = StandardScaler()
        features_scaled = scaler.fit_transform(features)
        # 计算轮廓系数
        silhouette_scores = []
        for k in range(2, 11):
            kmeans = KMeans(n_clusters=k, random_state=42)
            cluster_labels=kmeans.fit_predict(scaled_features)
            silhouette_avg = silhouette_score(scaled_features,cluster_labels)
            silhouette_scores.append(silhouette_avg)
        # 绘制轮廓系数曲线
        plt.plot(range(2, 11), silhouette_scores, marker='o')
        plt.title('Silhouette Method for Optimal k')
        plt.xlabel(' Number of clusters (k)')
        plt.ylabel('Silhouette Score')
        plt.show()
        
if __name__ == '__main__':
    cu = ClusterUtils()
    cu.get_k()

        
        
        
